package bbs;

import java.io.CharArrayReader;
import java.io.Reader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;

import oracle.sql.CLOB;

import org.apache.ibatis.session.SqlSession;

//회원정보를 처리하기 위한 모든 제어 구조
public class BBSMyba {

	private SqlSession session;//드라이버 로딩과 Connection 객체가 생성된 상태
	BBSVo bv;
	
	public BBSMyba() {
		try {
			session = BBSFactory.getFactory().openSession();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public BBSVo getBv() {
		return bv;
	}
	public void setBv(BBSVo bv) {
		this.bv = bv;
	}

	public boolean insert(){
		
		boolean flag = false;
		try {
			HashMap<String, Object> map = new HashMap<String, Object>();
			map.put("title", bv.getTitle());
			map.put("content", bv.getContent());
			int rs = session.insert("bbs.insert", map);
			if(rs==1){
				session.commit();
				flag = true;
			}else{
				session.rollback();
				flag = false;
			}
			session.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
		
	}
	
	public ArrayList<BBSVo> select(){
		ArrayList<BBSVo> list=null;
		list = (ArrayList<BBSVo>)session.selectList("bbs", bv);
		session.close();
		return list;
	}
	
	public BBSVo view(){
		BBSVo vo = (BBSVo)session.selectOne("bbs", bv);
		session.close();
		return vo;
	}
	
	public boolean delete(){
		boolean flag = false;
		int rs = session.delete("bbs", bv);
		if(rs==1){
			session.commit();
			flag = true;
		}else{
			session.rollback();
			flag = false;
		}
		session.close();
		return flag;
	}
	
	public boolean update(){
		boolean flag = false;
		try {
			int rs = session.update("bbs", bv);
			CLOB clob = (CLOB)session.selectOne("bbs.clob", bv);
			Writer writer = ((CLOB)clob).getCharacterOutputStream();
			Reader src = new CharArrayReader(bv.getContent().toCharArray());
			char[] buffer = new char[1024];
			int read=0;
			while((read = src.read(buffer,0,1024))!=-1){
				writer.write(buffer,0,read);//clob에 데이타를 넣는역할인듯
			}
			if(rs==1){
				session.commit();
				flag = true;
			}else{
				session.rollback();
				flag = false;
			}
			session.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return flag;
	}
	
}
